﻿using Core.Domain;
using Core.DomainServices;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.DomainServices
{
    public class FileParser: IDataParser
    {
        private HtmlAgilityPack.HtmlWeb htmlPack;
        private readonly IBodyParser<HtmlNodeCollection> bodyParser;
        private readonly IHeaderParser<HtmlNodeCollection> headerParser;

        public FileParser(IBodyParser<HtmlNodeCollection> bodyParser, IHeaderParser<HtmlNodeCollection> headerParser)
        {
            this.bodyParser = bodyParser;
            this.headerParser = headerParser;
        }

        public DataItem Parser(string file)
        {
            var item = new DataItem();
            htmlPack = new HtmlAgilityPack.HtmlWeb();
            var doc = htmlPack.Load(file);

            var patient = doc.DocumentNode.SelectNodes("//patient");
            item.Patient = headerParser.Parser(patient);

            var sections = doc.DocumentNode.SelectNodes("//section");
            foreach (var section in sections)
            {
                try
                {
                    var docx = new HtmlDocument();
                    docx.LoadHtml(section.InnerHtml);
                    var tables = docx.DocumentNode.SelectNodes("//table");
                    string tableName = docx.DocumentNode.SelectSingleNode("//title").InnerText;
                    if (tableName != null)
                    {
                        if (tableName == "FAMILY HISTORY") item.FamilyHistorys = bodyParser.Parser(tables);
                        if (tableName == "FUNCTIONAL STATUS") item.FunctionalStatuses = bodyParser.Parser(tables);
                        if (tableName == "Problems") item.Problems = bodyParser.Parser(tables);
                        if (tableName == "SOCIAL HISTORY") item.SocialHistorys = bodyParser.Parser(tables);
                        if (tableName == "Medications") item.Medications = bodyParser.Parser(tables);
                        
                    }
                    
                }catch(Exception ex){
                    string message = ex.Message;
                }
            }
            return item;
        }
        
        public void Dispose()
        {
            try
            {
                if (htmlPack != null)
                {
                    htmlPack = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch { }
        }
    }
}
